package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.SettingFromDto;
import cn.livingCloud.entity.system.Setting;
import cn.livingCloud.repository.SettingMapper;

/**
 * Created by DingJie  on 2016/1/20.
 */
public class SettingFromDtoUpdator {
    private transient SettingMapper mapper = BeanProvider.getBean(SettingMapper.class);
    private SettingFromDto fromDto;

    public SettingFromDtoUpdator(SettingFromDto settingFromDto) {
        this.fromDto = settingFromDto;
    }

    public void update() {
        Setting s = mapper.findSetting();
        if (s == null) {
            saveSetting(fromDto);
        } else {
            creatSetting(fromDto, s);
        }
    }

    private void creatSetting(SettingFromDto settingFromDto, Setting s) {
        s.setName(settingFromDto.getName());
        s.setNotes(settingFromDto.getNotes());
        s.setAppid(settingFromDto.getAppid());
        s.setSecret(settingFromDto.getSecret());
        s.setToken(settingFromDto.getToken());
        s.setTemplateId(settingFromDto.getTemplateId());
        s.setTemplateContent(settingFromDto.getTemplateContent());
        mapper.update(s);
    }

    private void saveSetting(SettingFromDto settingFromDto) {
        Setting setting = new Setting();
        setting.setName(settingFromDto.getName());
        setting.setNotes(settingFromDto.getNotes());
        setting.setAppid(settingFromDto.getAppid());
        setting.setSecret(settingFromDto.getSecret());
        setting.setToken(settingFromDto.getToken());
        setting.setTemplateId(settingFromDto.getTemplateId());
        setting.setTemplateContent(settingFromDto.getTemplateContent());
        mapper.save(setting);
    }
}
